<script setup>
import { ref } from 'vue';
import dayjs from 'dayjs';

const { params } = useRoute();

const mpp = useCookie('mpp');

const urlHome = useUrl();
const urlCutHome = urlHome.value.substring(0, urlHome.value.length - 1);

const image_link = useModalImage();

const isOpen = ref(false);

const finishButton = ref(true);
image_link.value = '';

const kom_edited = ref('');

const selectedTech = ref(0);
const selectedPol = ref(0);
const selectedLit = ref(0);
const selectedCadcam = ref(0);
const oneNar = ref({});
// const selectedTech = computed(() => oneNar.value.naryad.sdl_set.tech)
// const selectedPol = computed(() => oneNar.value.naryad.sdl_set.pol)
// const selectedLit = computed(() => oneNar.value.naryad.sdl_set.lit)
// const selectedCadcam = computed(() => oneNar.value.naryad.sdl_set.cadcam)

const file = ref(null);

const handleFileSelection = async (event) => {
    let formData = new FormData();
    let uploadedFile = event.target.files[0];
    console.log(uploadedFile);
    file.value = uploadedFile;
    formData.append('image', file.value)
    formData.append('naryad_id', params.id)

    const { data } = await useFetch(urlHome.value + 'lab/image_add', {
        headers: {
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'application/json',
        },
        method: 'POST',
        body: formData
    })
    imgListRefresh();
    return;
}

async function getNar() {
    const response = await useFetch(`${urlHome.value}lab/one_nar/`, {
        query: {
            naryad_id: params.id
        }
    })
    if (response) {
        console.log(response.data._value)
        oneNar.value = response.data._value
        selectedTech.value = oneNar.value.naryad.sdl_set.tech;
        selectedPol.value = oneNar.value.naryad.sdl_set.pol;
        selectedLit.value = oneNar.value.naryad.sdl_set.lit;
        selectedCadcam.value = oneNar.value.naryad.sdl_set.cadcam;
    }
}

getNar()

// const { data: oneNar } = await useFetch(`${urlHome.value}lab/one_nar`, {
//     query: {
//         naryad_id: params.id,
//     },
// })

// watch(oneNar, (newNar) => {
//     console.log(newNar)
//     selectedTech.value = toRaw(newNar).naryad.sdl_set.tech;
//     selectedPol.value = toRaw(newNar).naryad.sdl_set.pol;
//     selectedLit.value = toRaw(newNar).naryad.sdl_set.lit;
//     selectedCadcam.value = toRaw(newNar).naryad.sdl_set.cadcam;
// })

const { data: imgList, refresh: imgListRefresh } = await useFetch(`${urlHome.value}lab/image_list/`, {
    query: {
        naryad_id: params.id
    }
})

const { data: comments_list, refresh: comListRefresh } = await useFetch(`${urlHome.value}lab/comments_list`, {
    query: {
        naryad_id: params.id
    }
})


function openModalImage(image_url) {
    isOpen.value = true;
    image_link.value = image_url;
}


async function saveKom() {
    let formData = new FormData();
    formData.append('comment', kom_edited.value)
    formData.append('naryad_id', params.id)
    formData.append('mpp', mpp.value)

    const response = await $fetch(`${urlHome.value}lab/add_comment`, {
        method: 'POST',
        body: formData,
    })
    if (response.ok) {
        console.log(response.status);
        kom_edited.value = ''
        comListRefresh();
    } else {
        alert("Ошибка сохранения комментария " + response.message);
    }
}

async function moveTo(id, sdl) {
    // enableFinish.value = false
    console.log("id: ", id, " sdl: ", sdl, " mpp: ", mpp.value)
    const response = await $fetch(`${urlHome.value}lab/move_naryad`, {
        query: {
            naryad_id: id,
            sdl: sdl,
            mpp: mpp.value,
        }
    })

    if (response.ok) {
        console.log(response.status);
        await navigateTo('/lab/stlist');
    } else {
        alert("Ошибка передачи наряда " + response.message);
    }
}

const { data: specList } = await useFetch(`${urlHome.value}lab/list_all_prof/`)

async function addSpec(naryad_id) {
    // finishButton.value = false
    let formData = new FormData();
    formData.append('tech', selectedTech.value)
    formData.append('lit', selectedLit.value)
    formData.append('pol', selectedPol.value)
    formData.append('cadcam', selectedCadcam.value)
    formData.append('naryad_id', naryad_id)

    const response = await $fetch(`${urlHome.value}lab/sdl_set_update/`, {
        method: 'POST',
        body: formData
    })
    if (response.ok) {
        console.log(response.status);
        // kom_edited.value = ''
        // comListRefresh();
    } else {
        // alert("Ошибка сохранения комментария " + response.message);
    }

    // moveTo(naryad_id, 35);
    // navigateTo('/lab/stlist');
}

async function nextEtap(naryad_id) {
    addSpec(naryad_id)
    moveTo(naryad_id, 35);

}
</script>

<template>
    <div>
        <div>
            <div class="grid lg:grod-cols-2 md:grid-cols-2 sm:grid-cols-1">
                <div>Пациент: <b>{{ oneNar?.naryad?.patient?.fam }} {{ oneNar?.naryad?.patient?.im }} {{
                    oneNar?.naryad?.patient?.ot }}</b></div>
                <div>Дата рождения: <b>{{ oneNar?.naryad?.patient?.dr ?
                    dayjs(oneNar.naryad.patient.dr).format('DD.MM.YYYY') : "" }}</b></div>
                <div>Дата наряда: <b>{{ oneNar?.naryad?.dou ?
                    dayjs(oneNar.naryad.dou).format('DD.MM.YYYY') : "" }}</b></div>
                <div>Оплата: <b>{{ oneNar?.naryad?.opl?.name_opl }}</b></div>
                <div>Номер квитанции: <b>{{ oneNar?.naryad?.nkv }}</b></div>
                <div>Стоимость: <b>{{ oneNar?.naryad?.stu ? oneNar?.naryad?.stu.toLocaleString() : "" }} р.</b></div>
                <div>Врач: <b>{{ oneNar?.naryad?.naryad_doc?.user_full?.fam }} {{
                    oneNar.naryad?.naryad_doc?.user_full?.im }} {{
                            oneNar.naryad?.naryad_doc?.user_full?.ot
                        }}</b>
                </div>
            </div>
        </div>
        <br>
        <UInput color="green" type="file" accept="image/*" @change="handleFileSelection($event)"
            class="px-2 file-input w-full md:max-w-xs lg:max-w-xs xs:max-w-lg" />
        <br>
        <div class="px-2 grid grid-cols-4 gap-2 md:grid-cols-5 lg:grid-cols-5" v-auto-animate>
            <div v-for="image in imgList" :key="image">
                <img :src="urlCutHome + image" @click="openModalImage(image)" alt="image" class="w-16 md:w-24 lg:w-28">
            </div>
        </div>
        <div class="form-control px-2">
            <UInput v-model="kom_edited" @keyup.enter="saveKom" class="max-w-xs" color="primary" variant="outline"
                placeholder="Введите комментарий" />
            <UButton class="btn btn-sm my-1" v-if="kom_edited.length > 0" @click="saveKom">
                Добавить
                комментарий</UButton>
        </div>
        <div class="sm:grid grid-cols-4 gap-2">
            <div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
                <label class="label">
                    <span class="label-text ">Техник</span>
                </label>
                <USelect v-model="selectedTech" @change="addSpec(oneNar?.naryad?.id)" color="primary" variant="outline"
                    :options="specList.list_tech" option-attribute="name" value-attribute="mpp" />
            </div>

            <div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
                <label class="label">
                    <span class="label-text">Полировщик</span>
                </label>
                <USelect v-model="selectedPol" @change="addSpec(oneNar?.naryad?.id)" color="primary" variant="outline"
                    :options="specList.list_pol" option-attribute="name" value-attribute="mpp" />
            </div>

            <div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
                <label class="label">
                    <span class="label-text">Литейщик</span>
                </label>
                <USelect v-model="selectedLit" @change="addSpec(oneNar?.naryad?.id)" color="primary" variant="outline"
                    :options="specList.list_lit" option-attribute="name" value-attribute="mpp" />
            </div>

            <div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
                <label class="label">
                    <span class="label-text">CAD/CAM</span>
                </label>
                <USelect v-model="selectedCadcam" @change="addSpec(oneNar?.naryad?.id)" color="primary"
                    variant="outline" :options="specList.list_cadcam" option-attribute="name" value-attribute="mpp" />
            </div>
        </div>
        <br>
        <div
            class="grid grid-cols-1 md:justify-items-center lg:justify-items-center xl:justify-items-center 2xl:justify-items-center">
            <UButton label="Сохранить и передать в работу" v-if="oneNar?.naryad?.id_etap == 1"
                class="btn md:btn-wide md:btn-lg" @click="nextEtap(oneNar?.naryad?.id)" :disabled="!finishButton" />
        </div>
        <div class="flex justify-around">
            <div>
                <div class="px-2">Предыдущие этапы выполняли:</div>
                <ul class="steps steps-vertical px-2" v-auto-animate>
                    <li v-for="item in oneNar?.prev_etaps" class="step step-neutral break-word" :key="item.id">
                        <div class="text-left w-full">
                            <b>{{ item?.sdl?.name_sdl }}
                                {{ item?.user?.fam }} {{ item?.user?.im[0] }}. {{ item?.user?.ot[0]
                                }}.</b>
                            <br>
                        </div>
                    </li>
                    <li v-if="oneNar?.naryad?.user_etap_link?.login === 'none'" data-content="!"
                        class="step step-error">
                        Не назначен
                    </li>
                    <li v-else class="step step-accent">
                        <b>
                            {{ oneNar?.naryad?.sdl_oneNar?.naryad?.name_sdl }}
                            {{ oneNar?.naryad?.user_etap_link?.fam }}
                            {{ oneNar?.naryad?.user_etap_link?.im[0] }}.
                            {{ oneNar?.naryad?.user_etap_link?.ot[0] }}.
                        </b>
                    </li>
                </ul>
            </div>
            <div>
                Комментарии:
                <ul>
                    <li v-for="comment in comments_list">
                        <i><sub>{{ dayjs(comment.date).format('DD MMM HH:mm') }}</sub></i>
                        {{ comment.naryad.sdl_etap.name_sdl }} <b>{{ comment.user && comment.user.fam ? comment.user.fam
                            : "" }} {{ comment.user && comment.user.im ? comment.user.im[0] : "" }}. {{
                                comment.user && comment.user.ot ? comment.user.ot[0] : "" }}.</b> - {{
                                comment.comment }}
                    </li>
                </ul>
            </div>
        </div>
        <UModal v-model="isOpen" fullscreen>
            <UCard :ui="{
                base: 'h-full flex flex-col',
                rounded: '',
                divide: 'divide-y divide-gray-100 dark:divide-gray-800',
                body: {
                    base: 'grow'
                }
            }">
                <template #header>
                    <div class="flex items-center justify-between">
                        <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
                            <img :src="urlCutHome + image_link.value" alt="image">
                        </h3>
                        <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
                            @click="isOpen = false" />
                    </div>
                </template>
            </UCard>
        </UModal>
    </div>
</template>